<?php
/*
+---------------------------------------------------------------------------
|   Arka-Tech Web Application v1.2.0
|   ========================================
|   by Christopher Hall
|   (c) 2009 Arka-Tech Productions
|   http://arka-tech.net
|   ========================================
|   Web: http://www.SITENAME.com
|   Time: Sat, 28 Feb 2009 9:05 AM
|   Release: RmVicnVhcnkgMjAwOSBMYXVuY2ggNA==
|   Email: ArkahnX@gmail.com
|   Licence Info: http://www.arka-tech.net/default.php?page=license
+---------------------------------------------------------------------------
*/

function check_init() {
	// Check SAFE_MODE
	if (ini_get('safe_mode')) {
		$errors[] = lang_translate('installer-lib-check-safemode','Sorry, but ATWA needs SAFE_MODE to be set to OFF. Your current configuration has SAFE_MODE activated. Please modify your php.ini file to turn SAFE_MODE off, or ask your system administrator for more help.');
	}
	
	// Check PHP version
	$version = phpversion();
	if ($version{0} < 5) {
		$errors[] = lang_translate('installer-lib-check-php','Your server is currently using an unsupported version of PHP. Please update to PHP 5.0 or higher before installing ATWA.');
	}
	
	// Set install types
	if (file_exists('./CORE.inc.php')) {
		define('TYPE_INSTALL',0);
		include_once('./CORE.inc.php');
		$checked = check_versions(ATWA_VERSION,INSTALL_VERSION);
		if (!$checked) {
			define('TYPE_SYSTEM',1);
			define('TYPE_UPDATE',0);
		} elseif ($checked == 2) {
			define('TYPE_SYSTEM',0);
			if (file_exists('./ATWA/')) {
				define('TYPE_UPDATE',2);
			} else {
				define('TYPE_UPDATE',1);
			}
		} else {
			$errors[] = lang_translate('installer-lib-check-newer','The current ATWA installation is newer than this update. Please delete the directory "[installer]" for security reasons.',array('[installer]' => INSTALL_DIR));
		}
	} else {
		define('TYPE_UPDATE',0);
		define('TYPE_SYSTEM',0);
		if (file_exists('./ATWA/')) {
			define('TYPE_INSTALL',2);
		} else {
			define('TYPE_INSTALL',1);
		}
	}
	
	// Check file permissions
	unset($array);
	$array = array('./',INSTALL_DIR,INSTALL_DIR . 'index.php',INSTALL_DIR . 'files/index.php',INSTALL_DIR . 'files/CORE.inc.php');
	if (TYPE_UPDATE == 2) {
		$array[] = './ATWA/';
		$array[] = './CORE.inc.php';
		$array[] = INSTALL_DIR . 'files/update.xml';
	} elseif (TYPE_UPDATE) {
		$array[] = INSTALL_PACKAGE;
		$array[] = './CORE.inc.php';
		$array[] = INSTALL_DIR . 'files/update.xml';
	} elseif (TYPE_SYSTEM) {
		$array[] = './CORE.inc.php';
	} elseif (TYPE_INSTALL == 2) {
		$array[] = './ATWA/';
	} else {
		$array[] = INSTALL_PACKAGE;
	}
	$checked = check_permissions($array);
	if (file_exists(INSTALL_INDEX) && (!is_readable(INSTALL_INDEX) || !is_writable(INSTALL_INDEX)) && !@chmod(INSTALL_INDEX,0777)) {
		$errors[] = lang_translate('installer-lib-check-permissions','Warning: Please, give full permissions (CHMOD 777) to "[file]".',array('[file]' => INSTALL_INDEX));
	}
	if (is_array($checked) && is_array($errors)) {
		$errors = array_merge($errors,$checked);
	} elseif (is_array($checked)) {
		$errors = $checked;
	}
	
	// Check gzip support
	if (!function_exists('gzopen') && (TYPE_INSTALL === 1 || TYPE_UPDATE === 1)) {
		$errors[] = lang_translate('installer-lib-check-gzip','Your server does not seem to have gzip support. To install ATWA manually, rename "[package]" to "package.tar.gz" and extract the contents into the same directory.',array('[package]' => INSTALL_PACKAGE));
	}
	
	// Output errors
	if ($errors) {
		output_errors($errors);
	} else {
		return true;
	}
}

function check_permissions($files) {
	foreach ($files as $file) {
		if ($file == INSTALL_PACKAGE) {
			if (md5_file(INSTALL_PACKAGE) != INSTALL_MD5){
				$errors[] = lang_translate('installer-lib-check-md5','Warning: Please, check "[package]" since it seems to be corrupted.',array('[package]' => INSTALL_PACKAGE));
			}
		}
		if (!file_exists($file)) {
			$errors[] = lang_translate('installer-lib-check-notexist','Error: "[file]" does not exist.',array('[file]' => $file));
		} elseif (!is_readable($file) || !is_writable($file)) {
			if (!@chmod($file,0777)) {
				$errors[] = lang_translate('installer-lib-check-permissions','Warning: Please, give full permissions (CHMOD 777) to "[file]".',array('[file]' => $file));
			}
		}
	}
	if ($errors) {
		return $errors;
	} else {
		return true;
	}
}

function check_utf8() {
	$UTF8array = array();
	if (extension_loaded('mbstring') || function_exists('mb_substr') || preg_match('/^.{1}$/u',"ñ",$UTF8array) != 1) {
		return true;
	} else {
		return false;
	}
}

function check_version($one) {
	if (strrchr($one,'preview')) {
		$a[5] = substr(strrchr($one,'preview'),7);
		$one = substr($one,0,- strlen(strrchr($one,'preview')));
	} elseif (!$a[5]) {
		$a[5] = 9999;
	}
	if (strrpos($one,'-')) {
		$a[4] = substr(strrchr($one,'-'),1);
		$one = substr($one,0,- strlen(strrchr($one,'-')));
	}
	$one .= '.';
	if (strpos($one,'.') !== false) {
		$a[0] = substr($one,0,strpos($one,'.'));
		$one = substr($one,1 + strpos($one,'.'));
	}
	if (strpos($one,'.') !== false) {
		$a[1] = substr($one,0,strpos($one,'.'));
		$one = substr($one,1 + strpos($one,'.'));
	}
	if (strpos($one,'.') !== false) {
		$a[2] = substr($one,0,strpos($one,'.'));
		$one = substr($one,1 + strpos($one,'.'));
	}
	$a[3] = $one;
	for ($i = 0;$i < 6;$i++) {
		if ($a[$i] == 'x') {
			$a[$i] = 9999;
		} else {
			$a[$i] = floatval($a[$i]);
		}
	}
	ksort($a);
	return $a;
}

function check_versions($one,$two) {
	$one = check_version($one);
	$two = check_version($two);
	for ($i = 0;$i < 6;$i++) {
		if (intval($one[$i]) > intval($two[$i])) {
			return 1;
		} elseif (intval($one[$i]) < intval($two[$i])) {
			return 2;
		}
	}
	return 0;
}

function check_version_uasort($one,$two) {
	$checked = check_versions($one,$two);
	if ($checked == 2) {
		return -1;
	} else {
		return $checked;
	}
}

function lang_init() {
	if (!$_SESSION['lang'] || $_REQUEST['lang']) {
		$langs = lang_getAll(1);
		// Use lang from URL
		$request_lang = htmlspecialchars($_REQUEST['lang'],ENT_QUOTES,'UTF-8');
		if ($request_lang) {
			if (in_array($request_lang,$langs)) {
				$_SESSION['lang'] = $request_lang;
			} elseif (in_array(substr($request_lang,0,2),$langs)) {
				$_SESSION['lang'] = substr($request_lang,0,2);
			}
		}
		// Use lang from the user's browser
		if (!$_SESSION['lang']) {
			$temp_user_langs = explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
			foreach ($temp_user_langs as $user_lang) {
				$user_lang = substr($user_lang,0,strlen($user_lang) - strlen(strstr($user_lang,';')));
				$user_langs[] = substr($user_lang,0,strlen($user_lang) - strlen(strstr($user_lang,'-')));
			}
			foreach ($user_langs as $user_lang) {
				if (!$_SESSION['lang'] && in_array($user_lang,$langs)) {
					$_SESSION['lang'] = $user_lang;
				}
			}
			if (!$_SESSION['lang']) {
				foreach ($user_langs as $user_lang) {
					if (!$_SESSION['lang'] && in_array(substr($user_lang,0,2),$langs)) {
						$_SESSION['lang'] = substr($user_lang,0,2);
					}
				}
				// If the current session doesn't have a lang, set the default
				if (!$_SESSION['lang']) {
					$_SESSION['lang'] = 'en';
				}
			}
		}
	}
	
	global $translation;
	$translation = array();
	if (file_exists(INSTALL_DIR . 'langs/' . $_SESSION['lang'] . '/default.xml')) {
		$xml = xml_xml2array(file_get_contents(INSTALL_DIR . 'langs/' . $_SESSION['lang'] . '/default.xml'));
		foreach ($xml['translation'][0] as $key => $value) {
			$translation[$key] = $value[0];
		}
	}
}

function lang_getAll($easy = 0) {
	if ($easy) {
		$langs[] = 'en';
	} else {
		$temp_en['en']['author'] = 'ATWA Team';
		$temp_en['en']['name'] = 'English';
	}
	if ($handler = @opendir(INSTALL_DIR . 'langs/')) {
		while (($folder = readdir($handler)) !== false) {
			if ($folder != '.' && $folder != '..' && $folder != 'en' && file_exists(INSTALL_DIR . 'langs/' . $folder . '.xml')) {
				if ($easy) {
					$langs[] = $folder;
				} else {
					$xml = xml_xml2array(file_get_contents(INSTALL_DIR . 'langs/' . $folder . '.xml'));
					$temp_langs[$folder]['author'] = $xml['lang'][0]['author'][0];
					$temp_langs[$folder]['name'] = $xml['lang'][0]['name'][0];
				}
			}
		}
		closedir($handler);
	}
	if ($easy) {
		sort($langs);
		return $langs;
	} else {
		ksort($temp_langs);
		return array_merge($temp_en,$temp_langs);
	}
}

function lang_translate($key,$value,$tokens = array()) {
	global $translation;
	if (isset($translation[$key])) {
		$return = $translation[$key];
	} else {
		$return = $value;
	}
	foreach ($tokens as $key_array => $value_array) {
		$return = str_replace($key_array,$value_array,$return);
	}
	return $return;
}

function output_do($content,$style,$title = '',$langselector = 1) {
	header('Vary: Accept');
	if (!$_SERVER['HTTP_ACCEPT'] || stristr($_SERVER['HTTP_ACCEPT'],'application/xhtml+xml')) {
		header('Content-Type: application/xhtml+xml; charset=UTF-8');
	} else {
		header('Content-Type: text/html; charset=UTF-8');
	}
	echo '<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="' . $_SESSION['lang'] . '">
	<head>
		<meta http-equiv="content-language" content="' . $_SESSION['lang'] . '" />
		<meta http-equiv="content-style-type" content="text/css" />
		<meta http-equiv="content-script-type" content="text/javascript" />
		<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
		<link rel="shortcut icon" href="./output/images/favicon.ico" />
		<link rel="stylesheet" type="text/css" href="./output/styles/default.css" />';
		if ($style) {
			echo '<link rel="stylesheet" type="text/css" href="./output/styles/' . $style . '.css" />';
		}
		echo '<title>' . lang_translate('installer-lib-output-title','ATWA Installation') . '</title>
	</head>
	<body>
		<div class="background">
			<div class="window">
				<div class="logo"><br /><br /><br />&nbsp;'.INSTALLER_VERSION.'</div>';
	if (!check_utf8()) {
		echo '<div class="warning" style="color: red;">' . lang_translate('installer-lib-output-utf8','Your PHP version does not have full UTF-8 support. Please consider updating PHP or installing the mbstring module. Without it, you will be able to install and update your ATWA, but you may encounter problems in some areas of the system that require internationalization support.') . '</div>';
	}
	if ($title) {
		echo '<div class="title">' . $title . '</div>';
	}
	echo $content;
	if ($langselector) {
		/*echo '<form action="index.php" method="get">
	<div style="bottom: 10px; position: absolute; right: 10px;">';
		$requests = '';
		foreach ($_REQUEST as $key => $value) {
			if ($key != 'lang') {
				$requests .= '&amp;' . @htmlentities($key,ENT_QUOTES,'UTF-8') . '=' . @htmlentities($value,ENT_QUOTES,'UTF-8');
				echo '<input type="hidden" name="' . @htmlentities($key,ENT_QUOTES,'UTF-8') . '" value="' . @htmlentities($value,ENT_QUOTES,'UTF-8') . '" />';
			}
		}
		echo '<select name="lang" onchange="window.location = \'index.php?lang=\' + this.value + \'' . $requests . '\';">
	<optgroup label="' .  lang_translate('installer-lib-output-lang-currentlang','Current language') . '">';
		$echo = '';
		foreach (lang_getAll() as $lang => $array) {
			if ($lang == $_SESSION['lang']) {
				echo '<option value="' . $lang . '" selected="selected" title="' . lang_translate('installer-lib-output-lang-by','by') . ' ' . htmlspecialchars($array['author'],ENT_QUOTES,'UTF-8') . '">' . htmlspecialchars($array['name'],ENT_QUOTES,'UTF-8') . '</option></optgroup><optgroup label="' . lang_translate('installer-lib-output-lang-langs','Languages') . '">';
			} elseif ($lang == 'en') {
				$echo .= '<option value="' . $lang . '" title="' . lang_translate('installer-lib-output-lang-by','by') . ' ' . htmlspecialchars($array['author'],ENT_QUOTES,'UTF-8') . '">' . htmlspecialchars($array['name'],ENT_QUOTES,'UTF-8') . '</option>';
			} else {
				$echo .= '<option value="' . $lang . '" title="' . lang_translate('installer-lib-output-lang-by','by') . ' ' . htmlspecialchars($array['author'],ENT_QUOTES,'UTF-8') . '">' . htmlspecialchars($array['name'],ENT_QUOTES,'UTF-8') . '</option>';
			}
		}
		echo $echo . '</optgroup>
		</select>
		<input class="iButton" style="padding-left: 6px; padding-right: 6px;" type="submit" value="&gt;" />
	</div>
</form>';*/
	}
	echo '</div>
		</div>
	</body>
</html>';
	exit;
}

function output_errors($errors,$button = -1,$langselector = 1) {
	if ($button == -1) {
		$button = array('./index.php','Try again!');
	}
	$content = '<div class="errors"><ol>';
	foreach ($errors as $error) {
		$content .= '<li><span style="color: red;">' . $error . '</span></li>';
	}
	$content .= '</ol></div><div class="button"><form action="' . $button[0] . '" method="post"><input class="iButton" type="submit" value="' . $button[1] . '" /></form></div>';
	output_do($content,0,lang_translate('installer-lib-output-errors','There were problems during installation:'),$langselector);
}

function output_remove($location = './../index.php') {
	if (file_exists(INSTALL_INDEX)) {
		path_delete(INSTALL_INDEX);
	}
	if (file_exists(INSTALL_PACKAGE)) {
		path_delete(INSTALL_PACKAGE);
	}
	path_delete(INSTALL_DIR);
	header('Location: ' . $location);
	exit;
}

function output_uninstall() {
	include_once('CORE.inc.php');
	path_delete('./' . REAL_OS_ROOT . '/');
	path_delete('./index.php');
	path_delete('./license.txt');
	path_delete('./README.txt');
	path_delete('./CORE.inc.php');
	output_remove('http://ATWA.org/?section=uninstalled&lang=' . $_SESSION['lang']);
}

function path_account($user) {
	include_once('CORE.inc.php');
	$user_acronym = $user{0} . substr($user,-1) . substr(strlen($user),-1);
	return OS_ROOT . '/' . REAL_OS_ROOT . '/' . ACCOUNT_DIR . '/' . $user_acronym . '/' . $user . '.xml';
}

function path_delete($path) {
	if (is_file($path)) {
		return @unlink($path);
	} elseif ($handler = @opendir($path . '/')) {
		while (false !== ($file = readdir($handler))) {
			if ($file != '.' && $file != '..') {
				path_delete($path . '/' . $file);
			}
		}
		closedir($handler);
	}
	return @rmdir($path . '/');
}

function path_move($path,$dest) {
	if (@rename($path,$dest)) {
		return true;
	} elseif (is_file($path)) {
		@unlink($dest);
		return @rename($path,$dest);
	} else {
		if (!file_exists($dest . '/')) {
			@mkdir($dest . '/');
		}
		if ($handler = @opendir($path . '/')) {
			while (false !== ($file = readdir($handler))) {
				if ($file != '.' && $file != '..') {
					path_move($path . '/' . $file,$dest . '/' . $file);
				}
			}
			closedir($handler);
		}
		return @rmdir($path . '/');
	}
}

function xml_array2xml($array,$tabs = -1) {
	$tabs++;
	foreach ($array as $key => $value) {
		$key = htmlspecialchars($key,ENT_NOQUOTES,'UTF-8');
		$key = str_replace('?','&#63;',$key);
		$key = str_replace('!','&#33;',$key);
		$key = str_replace(' ','&nbsp;',$key);
		$key = str_replace('/','&#47;',$key);
		if (is_array($value)) {
			foreach ($value as $current) {
				$return .= str_pad('',$tabs,"\t") . '<' . $key . '>';
				if (is_array($current)) {
					$return .= "\n" . xml_array2xml($current,$tabs) . "\n" . str_pad('',$tabs,"\t");
				} else {
					$return .= htmlspecialchars($current,ENT_NOQUOTES,'UTF-8');
				}
				$return .= '</' . $key . '>' . "\n";
			}
		}
	}
	return trim($return,"\n");
}

function xml_xml2array($content) {
	$content_old = $content;
	$content = strstr($content,'<');
	$end = strstr($content,'>');
	if (!$content || !$end) {
		return html_entity_decode($content_old,ENT_QUOTES,'UTF-8');
	}
	while ($content && $end) {
		$full_tag = substr($content,1,-strlen($end));
		if (strpos($full_tag,' ')) {
			$tag = substr($full_tag,0,strpos($full_tag,' '));
		} else {
			$tag = $full_tag;
		}
		if ($tag{0} == '/' || $full_tag{strlen($full_tag) - 1} == '/') {
			$content = substr($end,1);
		} elseif ($tag{0} == '?') {
			$content = substr(strstr($content,'?>'),2);
		} elseif (substr($tag,0,3) == '!--') {
			$content = substr(strstr($content,'-->'),3);
		} else {
			$tag_end = strstr($content,'</' . $tag . '>');
			$tag_content = substr($end,1,strlen($end) - 1 - strlen($tag_end));
			$tag_end = substr($tag_end,strlen('</' . $tag . '>'));
			while ((substr_count($tag_content,'<' . $tag . '>') + substr_count($tag_content,'<' . $tag . ' ') - substr_count($tag_content,'<' . $tag . ' />')) && $tag_end) {
				$tag_end = strstr($tag_end,'</' . $tag . '>');
				$tag_content = substr($end,1,strlen($end) - 1 - strlen($tag_end));
				$tag_end = substr($tag_end,strlen('</' . $tag . '>'));
			}
			$content = $tag_end;
			$tag = html_entity_decode($tag,ENT_QUOTES,'UTF-8');
			$return[$tag][] = xml_xml2array($tag_content);
		}
		$content = strstr($content,'<');
		$end = strstr($content,'>');
	}
	return $return;
}
?>